import axios from 'axios'
import {get} from 'lodash'
import router from '@/router'
import {Message} from 'element-ui';

// 创建一个 axios 实例
const request = axios.create({
    baseURL: 'http://localhost:8000/',
    timeout: 5000,
})
// 请求拦截
request.interceptors.request.use(
    config => {
        let localToken = localStorage.getItem('token')
        if (localToken) {
            //携带请求头参数
            config.headers = {'Authorization': "token " + localToken};
        }
        return config
    },
    error => {
        // 发送失败
        return Promise.reject(error)
    }
)
// 响应拦截
request.interceptors.response.use(
    response => {
        // 2xx 范围内的状态码都会触发该函数。
        // 对响应数据做点什么
        if (response.status < 400) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
        // return Promise.resolve(response);
    },
    error => {
        const status = get(error, 'response.status')
        switch (status) {
            case 400:
                error.message = '请求错误'
                break
            case 401:
                error.message = '未认证，请登录'
                localStorage.removeItem('token')
                router.push({name: 'login'})
                break
            case 403:
                error.message = '拒绝访问'
                break
            case 404:
                error.message = `请求地址出错: ${error.response.config.url}`
                break
            case 408:
                error.message = '请求超时'
                break
            case 500:
                error.message = '服务器内部错误'
                break
            case 501:
                error.message = '服务未实现'
                break
            case 502:
                error.message = '网关错误'
                break
            case 503:
                error.message = '服务不可用'
                break
            case 504:
                error.message = '网关超时'
                break
            case 505:
                error.message = 'HTTP版本不受支持'
                break
            default:
                break
        }
        // Message.error(`${error.message}，URL：${error.config.url}，${(error.response && error.response.data.message || '')}`)
        Message.error(`${error.message}，${(error.response && error.response.data.message || '')}`)
        return Promise.reject(error)
    }
)

export default request

// 刷新token
const refreshTken = function () {
    const refresh = localStorage.getItem('refresh')
    return request({
        url: 'api/token/refresh/',
        method: 'post',
        data: {
            refresh: refresh
        }
    })
}


